package com.gxuwz.stats.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gxuwz.stats.entity.ResearchPlatform;
import com.gxuwz.stats.entity.ResearchProject;
import com.gxuwz.stats.entity.TotalWork;
import com.gxuwz.stats.entity.User;
import com.gxuwz.stats.security.jwt.JwtTokenUtil;
import com.gxuwz.stats.service.ResearchProjectService;
import com.gxuwz.stats.service.UserService;
import com.gxuwz.stats.utils.ExcelExportUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 超级管理员-科研项目工作量
 */
@RestController
@RequestMapping("/researchProject")
public class ResearchProjectController {

    @Autowired
    private ResearchProjectService researchProjectService;
    @Autowired
    private UserService userService;

    /**
     * 分页查询
     * @param params
     * @param currentPage
     * @param pageSize
     * @return
     */
    @GetMapping("/researchProjectList")
    public ResponseEntity<Map<String, Object>> researchProjectList(
            @RequestParam Map<String, String> params,
            @RequestParam(defaultValue = "1") int currentPage,
            @RequestParam(defaultValue = "10") int pageSize) {
        try {
            // 创建 MyBatis Plus 的 Page 对象进行分页查询
            IPage<ResearchProject> page = new Page<>(currentPage, pageSize);
            QueryWrapper<ResearchProject> queryWrapper = new QueryWrapper<>();

            // 根据用户名获取用户ID列表并加入查询条件
            if (params.containsKey("username") && !params.get("username").trim().isEmpty()) {
                List<String> userIds = userService.getUserIdsByKeyword(params.get("username"));
                if (!userIds.isEmpty()) {
                    queryWrapper.in("user_id", userIds);
                } else {
                    // 如果没有找到对应的userId，则返回空结果
                    queryWrapper.eq("1", "0");
                }
            }
            // 其他查询条件
            if (params.containsKey("projectName") && !params.get("projectName").isEmpty()) {
                queryWrapper.like("project_name", params.get("projectName"));
            }
            if (params.containsKey("projectCategory") && !params.get("projectCategory").isEmpty()) {
                queryWrapper.like("project_category", params.get("projectCategory"));
            }
            if (params.containsKey("projectLevel") && !params.get("projectLevel").isEmpty()) {
                queryWrapper.like("project_level", params.get("projectLevel")); // 确保数据库中有此字段
            }
            if (params.containsKey("projectStatus") && !params.get("projectStatus").isEmpty()) {
                queryWrapper.eq("project_status", params.get("projectStatus")); // 确保数据库中有此字段
            }
            // 立项时间按年份查
            if (params.containsKey("projectYear") && params.get("projectYear") != null && !params.get("projectYear").isEmpty()) {
                queryWrapper.apply("YEAR(project_year) = {0}", params.get("projectYear"));
            }
// 结题时间按年份查
            if (params.containsKey("projectEndYear") && params.get("projectEndYear") != null && !params.get("projectEndYear").isEmpty()) {
                queryWrapper.apply("YEAR(project_end_year) = {0}", params.get("projectEndYear"));
            }

            // 精确查询条件 - 项目立项提交状态
            if (params.containsKey("approvalStatus") && params.get("approvalStatus") != null && !params.get("approvalStatus").isEmpty()) {
                queryWrapper.eq("approval_status", params.get("approvalStatus"));
            }

            // 精确查询条件 - 项目立项审核状态
            if (params.containsKey("approvalReviewStatus") && params.get("approvalReviewStatus") != null && !params.get("approvalReviewStatus").isEmpty()) {
                queryWrapper.eq("approval_review_status", params.get("approvalReviewStatus"));
            }

            // 精确查询条件 - 项目结题提交状态
            if (params.containsKey("conclusionStatus") && params.get("conclusionStatus") != null && !params.get("conclusionStatus").isEmpty()) {
                queryWrapper.eq("conclusion_status", params.get("conclusionStatus"));
            }

            // 精确查询条件 - 项目结题审核状态
            if (params.containsKey("conclusionReviewStatus") && params.get("conclusionReviewStatus") != null && !params.get("conclusionReviewStatus").isEmpty()) {
                queryWrapper.eq("conclusion_review_status", params.get("conclusionReviewStatus"));
            }



            // 调用 service 层的分页查询方法
            IPage<ResearchProject> resultPage = researchProjectService.getAdminReProjectListWithUserInfo(page, queryWrapper);

            // 构造返回结果
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "查询成功");
            response.put("data", resultPage.getRecords()); // 当前页数据
            response.put("total", resultPage.getTotal()); // 总记录数
            response.put("currentPage", resultPage.getCurrent()); // 当前页码
            response.put("pageSize", resultPage.getSize()); // 每页大小
            response.put("totalPages", resultPage.getPages()); // 总页数

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "查询失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }

    @PostMapping("/importData")
    public ResponseEntity<Map<String, Object>> importData(@RequestParam("file") MultipartFile file) {
        try {
            researchProjectService.importResearchProjectData(file);
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "数据导入成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "数据导入失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }

    /**
     * 新增
     */
    @PostMapping("/addResearchProject")
    public ResponseEntity<Map<String, Object>> addResearchProject(@RequestBody ResearchProject researchProject) {
        System.out.println("===" + researchProject);

        String username = researchProject.getUsername(); // 从前端获取的用户名
        if (username == null || username.isEmpty()) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 400);
            response.put("msg", "用户名不能为空");
            return ResponseEntity.badRequest().body(response);
        }
        // 根据用户名获取用户信息
        User user = userService.getOne(new QueryWrapper<User>().eq("username", username));
        if (user == null) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 400);
            response.put("msg", "用户不存在");
            return ResponseEntity.badRequest().body(response);
        }

        String userId = user.getUserId();

//        // 判断该用户是否已经在 total_work 表中存在记录
//        QueryWrapper<ResearchProject> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("user_id", userId);
//        int count = researchProjectService.count(queryWrapper);
//
//        if (count > 0) {
//            Map<String, Object> response = new HashMap<>();
//            response.put("code", 400);
//            response.put("msg", "该用户已存在，不能重复新增");
//            return ResponseEntity.badRequest().body(response);
//        }

        // 设置 userId 并保存
        researchProject.setUserId(userId);

        // 1. 自动计算分值
        int baseScore = researchProjectService.getScoreByType(researchProject.getProjectCategory());
        researchProject.setProjectScore(baseScore);

        // 2. 计算总分值
        researchProjectService.calculateTotalScore(researchProject);

        researchProject.setApprovalSubmissionTime(LocalDateTime.now());
        researchProject.setConclusionSubmissionTime(LocalDateTime.now());
        researchProject.setApprovalStatus("已提交");
        researchProject.setApprovalReviewStatus("未审核");
        researchProject.setConclusionStatus("已提交");
        researchProject.setConclusionReviewStatus("未审核");

        researchProjectService.save(researchProject);

        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("msg", "新增成功");
        return ResponseEntity.ok(response);
    }

    /**
     * 删除
     * @param projectIds
     * @return
     */
    @DeleteMapping("/deleteResearchProject")
    public ResponseEntity<Map<String, Object>> deleteResearchProject(@RequestBody List<Long> projectIds) {
        System.out.println("删除：" + projectIds);
        researchProjectService.removeByIds(projectIds);

        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("msg", "删除成功");
        return ResponseEntity.ok(response);
    }

    /**
     * 修改
     * @param researchProject
     * @return
     */
    @PutMapping("/editResearchProject")
    public ResponseEntity<Map<String, Object>> editResearchProject(@RequestBody ResearchProject researchProject) {
//        System.out.println("user::" + researchProject);
        // 1. 获取前端传递的用户名
        String username = researchProject.getUsername();
//        System.out.println("shdjs="+username);
        if (username != null && !username.isEmpty()) {
            // 2. 查询用户信息
            User user = userService.getOne(new QueryWrapper<User>().eq("username", username));
//            System.out.println("user="+user);
            if (user == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("code", 400);
                response.put("msg", "用户不存在");
                return ResponseEntity.badRequest().body(response);
            }
            // 3. 设置 userId
            researchProject.setUserId(user.getUserId());
        }

        // 1. 自动计算分值
        int baseScore = researchProjectService.getScoreByType(researchProject.getProjectCategory());
        researchProject.setProjectScore(baseScore);

        // 2. 计算总分值
        researchProjectService.calculateTotalScore(researchProject);
        researchProjectService.updateById(researchProject);

        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("msg", "修改成功");
        return ResponseEntity.ok(response);
    }

    @PostMapping("/reviewResearchProject")
    public ResponseEntity<Map<String, Object>> reviewResearchProject(@RequestBody Map<String, Object> params) {
        Map<String, Object> response = new HashMap<>();
        try {
            Long projectId = Long.valueOf(params.get("projectId").toString());
            String reviewType = params.get("reviewType").toString(); // "approval" 或 "conclusion"
            String reviewStatus = params.get("reviewStatus").toString(); // 审核通过/审核不通过
            String reviewResult = params.get("reviewResult") != null ? params.get("reviewResult").toString() : "";

            ResearchProject researchProject = researchProjectService.getById(projectId);
            if (researchProject == null) {
                response.put("code", 404);
                response.put("msg", "数据不存在");
                return ResponseEntity.ok(response);
            }

            if ("approval".equals(reviewType)) {
                // 审核立项
                researchProject.setApprovalReviewStatus(reviewStatus);
                researchProject.setApprovalReviewTime(LocalDateTime.now());
                researchProject.setApprovalReviewResult(reviewResult);

                if ("审核不通过".equals(reviewStatus)) {
                    researchProject.setApprovalStatus("未提交");
                } else if ("审核通过".equals(reviewStatus)) {
                    // 当立项审核通过后，设置项目状态为结题
                    researchProject.setProjectStatus("结题");
                }

            } else if ("conclusion".equals(reviewType)) {
                // 审核结题前，先校验立项是否通过
                if (!"审核通过".equals(researchProject.getApprovalReviewStatus())) {
                    response.put("code", 400);
                    response.put("msg", "请先立项审核通过，才能审核结题！");
                    return ResponseEntity.ok(response);
                }
                researchProject.setConclusionReviewStatus(reviewStatus);
                researchProject.setConclusionReviewTime(LocalDateTime.now());
                researchProject.setConclusionReviewResult(reviewResult);
                if ("审核不通过".equals(reviewStatus)) {
                    researchProject.setConclusionStatus("未提交");
                }
            } else {
                response.put("code", 400);
                response.put("msg", "未知的审核类型");
                return ResponseEntity.ok(response);
            }

            researchProjectService.updateById(researchProject);

            response.put("code", 200);
            response.put("msg", "审核成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("code", 500);
            response.put("msg", "审核失败：" + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    @GetMapping("/export")
    public void exportResearchProject(
            @RequestParam(value = "year", required = false) String year,
            HttpServletResponse response) throws Exception {

        // 3. 查询 ResearchProject（可按年份筛选）
        QueryWrapper<ResearchProject> queryWrapper = new QueryWrapper<>();

        if (year != null && !year.isEmpty()) {
            queryWrapper.like("project_year", year.substring(0, 4));
        }

        // 只导出立项审核通过或结题审核通过的数据
        queryWrapper.and(qw ->
                qw.eq("approval_status", "已提交")
                        .or()
                        .eq("conclusion_status", "已提交")
        );

        List<ResearchProject> list = researchProjectService.list(queryWrapper);

        // 4. 查询所有用户，构建 userId -> username 映射
        List<User> userList = userService.list();
        Map<String, String> userIdNameMap = userList.stream()
                .collect(Collectors.toMap(User::getUserId, User::getUsername, (a, b) -> a));
        for (ResearchProject w : list) {
            w.setUsername(userIdNameMap.getOrDefault(w.getUserId(), ""));
        }

        // 5. 给每条数据加序号
        for (int i = 0; i < list.size(); i++) {
            list.get(i).setRowNum(i + 1); // 从1开始
        }

        // 6. 生成文件名
        String now = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date());
        String fileName = "科研项目工作量-" + now + ".xlsx";

        // 7. 导出
        ExcelExportUtil.export(response, list, ResearchProject.class, "科研项目工作量", fileName);
    }
}
